#include "P3Error.h"

using namespace std;

// Make sure ios_base is properly initialized before our OutStreams are
// constructed.
static ios_base::Init ios_base_Init_;

// Definitions of the actual global objects.
P3Error::OutStream p3err__;
P3Error::OutStream p3out__;
P3Error::OutStream p3dbg__;

namespace P3Error
{

string OutStream::sContext = "";
//int    OutStream::sDebugLevel = 0;

OutStream& OutStream::operator()( const char* inContext )
{
  if( sContext.empty() )
    mBuf.SetContext( inContext );
  else
    ( *this )();
  return *this;
}

OutStream& OutStream::operator()()
{
  mBuf.SetContext( sContext );
  return *this;
}
/*
OutStream& OutStream::Debug( int inDebugLevel )
{
  if( sDebugLevel >= inDebugLevel )
    rdbuf( &mBuf );
  else
    rdbuf( NULL );
  return *this;
}
*/
OutStream::FlushHandler OutStream::StringBuf::SetFlushHandler( OutStream::FlushHandler f )
{
  if( str().length() > 1 )
  {
    string message = mContext.empty() ? str() : mContext + ": " + str();
    if( mpOnFlush )
      mpOnFlush( message );
    else if( f )
      f( message );
  }
  str( "" );
  FlushHandler h = mpOnFlush;
  mpOnFlush = f;
  return h;
}

int OutStream::StringBuf::sync()
{
  int r = stringbuf::sync();
  ++mNumFlushes;
  SetFlushHandler( mpOnFlush );
  return r;
}

} // namespace P3Error

